package com.leyou.cart.service.impl;

import com.leyou.cart.pojo.Cart;
import com.leyou.cart.service.CartService;
import com.leyou.common.auth.entity.UserInfo;
import com.leyou.common.enums.LyExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.threadlocals.UserHolder;
import com.leyou.common.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String LY_CART_KEY="ly:cart:key:";

    @Override
    public void addCart(Cart cart) {
        // 1获取用户信息  13112345678
        UserInfo user = UserHolder.getUser();
        Long userId = user.getId();
        String key=LY_CART_KEY+userId;
        //2 基于用户信息作为key从redis中获取购物车列表 hash
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(key);
        //保存购物车数据到redis中
        addCartToRedis(cart, hashOps);


    }

    /**
     * 保存购物车数据到redis中
     * @param cart
     * @param hashOps
     */
    private void addCartToRedis(Cart cart, BoundHashOperations<String, String, String> hashOps) {
        //3 判断redis中是否有页面传递的购物车商品数据
        String skuId = cart.getSkuId().toString();
        Boolean boo = hashOps.hasKey(skuId);
        Integer num = cart.getNum();
        //3.1 如果存在，修改购物车商品数据
        if(boo!=null && boo){
            //获取redis中的购物车对象 json格式字符串
            cart =  JsonUtils.toBean(hashOps.get(skuId),Cart.class);
            cart.setNum(cart.getNum()+num);
        }

        //3.2 如果不存在，将页面传递的购物车对象，存入redis中
        hashOps.put(skuId,JsonUtils.toString(cart));
    }

    @Override
    public List<Cart> queryCartList() {
        // 1获取用户信息
        UserInfo user = UserHolder.getUser();
        Long userId = user.getId();
        String key=LY_CART_KEY+userId;
        //2 基于用户信息作为key从redis中获取购物车列表 hash  key:skuId  value:cart
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(key);
        //获取redis中当前用户的购物车列表  json字符串
        List<String> cartListStr = hashOps.values();

        List<Cart> cartList = cartListStr.stream().map(json -> {
            return JsonUtils.toBean(json, Cart.class);
        }).collect(Collectors.toList());
        return cartList;
    }

    @Override
    public void updateNum(Long skuId, Integer num) {
        // 1获取用户信息
        UserInfo user = UserHolder.getUser();
        Long userId = user.getId();
        String key=LY_CART_KEY+userId;
        String skuIdStr = skuId.toString();
        //2 基于用户信息作为key从redis中获取购物车列表 hash  key:skuId  value:cart
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(key);
        Boolean boo = hashOps.hasKey(skuIdStr);
        if (boo==null || !boo) {
            throw new LyException(LyExceptionEnum.CARTS_NOT_FOUND);
        }
        //3 更新购物车中商品数量
        Cart cart = JsonUtils.toBean(hashOps.get(skuIdStr), Cart.class);
        cart.setNum(num);
        //4 将更新结果，重新写回redis
        hashOps.put(skuIdStr,JsonUtils.toString(cart));
    }

    @Override
    public void deleteCart(Long skuId) {
        // 1获取用户信息
        UserInfo user = UserHolder.getUser();
        Long userId = user.getId();
        String key=LY_CART_KEY+userId;
        String skuIdStr = skuId.toString();
        //2 基于用户信息作为key从redis中获取购物车列表 hash  key:skuId  value:cart
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(key);
        Boolean boo = hashOps.hasKey(skuIdStr);
        if (boo==null || !boo) {
            throw new LyException(LyExceptionEnum.CARTS_NOT_FOUND);
        }

        hashOps.delete(skuIdStr);

    }

    @Override
    public void addCartList(List<Cart> cartList) {
        // 1获取用户信息  13112345678
        UserInfo user = UserHolder.getUser();
        Long userId = user.getId();
        String key=LY_CART_KEY+userId;
        //2 基于用户信息作为key从redis中获取购物车列表 hash
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(key);
        //保存购物车数据到redis中
        for (Cart cart : cartList) {
            addCartToRedis(cart, hashOps);
        }
    }
}
